<template>
  <div class="form-page">
    
     
    <div class="form-group">



      <!-- 添加其他 pin 数据字段 -->


      <form @submit="handleSubmit">


        <div class="form-group">
        <label>NFT name:</label>
        <input type="text" v-model="nftName">
      </div>

              <!-- 合约符号 -->
      <div class="form-group">
        <label>NFT symbol:</label>
        <input type="text" v-model="symbol">
      </div>
           <!-- 铸造总数量 -->
      <div class="form-group">
        <label>铸造总数量:</label>
        <input type="number" v-model="totalMintAmount">
      </div>

      <!-- 代币合约地址 -->
      <div class="form-group">
        <label>地址:</label>
        <input type="text" v-model="tokenContractAddress">
      </div>
      <!-- 发行价格 -->
      <div class="form-group">
        <label>发行价格:</label>
        <input type="text" v-model="issuePrice">
      </div>
    
      <button type="submit">提交</button>
      
      </form>
   
   
  </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import {
		notify
	} from "@kyvg/vue3-notification";
 //交互
 import * as anchor from "@coral-xyz/anchor";

//import { Nftmint } from "../types/nftmint";
import { Keypair, PublicKey, SYSVAR_RENT_PUBKEY, SystemProgram ,LAMPORTS_PER_SOL} from "@solana/web3.js";
import { AnchorError } from '@coral-xyz/anchor';
import { ASSOCIATED_PROGRAM_ID, TOKEN_PROGRAM_ID, associatedAddress } from "@coral-xyz/anchor/dist/cjs/utils/token";
import { BN } from "bn.js";

import { useWallet } from 'solana-wallets-vue'
const METADATA_PROGRAM = new PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");

import store from '../vuex';

const route = useRoute();

const pinData_string = route.query.pinData;

console.log(pinData_string);
const pinData =JSON.parse(pinData_string);
const meta = JSON.parse(pinData.jsonContent);

 const nftName = ref('');
 const symbol = ref('');
const totalMintAmount = ref(0);
const tokenContractAddress = ref('5Bfrz12Sj7jnKvT3zbYpyHhrXDVHPXwyESJUPrx6SsPe');
const issuePrice = ref(0);


async function create() {
  const workspaceValue = store.state.workspace.value;
if (!workspaceValue) {
  console.error('Workspace is not initialized.');
  return;
}

//组装数据

const uri = "https://ipfs.io/ipfs/"+pinData.ipfs_pin_hash;
const nameValue = nftName.value;
const symbolValue = symbol.value;
const totalMintAmountValue = totalMintAmount.value;

const tokenContractAddressValue = tokenContractAddress.value;
let issuePriceValue = issuePrice.value;


let timestamp = Math.floor(new Date().getTime() / 1000);


const { wallet, connection, provider, program } = workspaceValue;
console.log("program.programId:",program.programId);
const [collectionPDA] = anchor.web3.PublicKey.findProgramAddressSync(
  [Buffer.from("collection"), new BN(timestamp).toArrayLike(Buffer, "le", 8)],
  program.programId
);

console.log("wallet", provider.wallet.publicKey.toBase58());
  let collectionMetadataPDA = anchor.web3.PublicKey.findProgramAddressSync(
    [Buffer.from("metadata"), METADATA_PROGRAM.toBytes(), collectionPDA.toBytes()],
    METADATA_PROGRAM
  )[0];
  console.log("collectionMetadataPDA", collectionMetadataPDA.toBase58());

  let collectionMasterEditionPDA = anchor.web3.PublicKey.findProgramAddressSync(
    [Buffer.from("metadata"), METADATA_PROGRAM.toBytes(), collectionPDA.toBytes(), Buffer.from("edition")],
    METADATA_PROGRAM
  )[0];
  console.log("collectionMasterEditionPDA", collectionMasterEditionPDA.toBase58());

  const collectionTokenAccount = await associatedAddress({
    mint: collectionPDA,
    owner: provider.wallet.publicKey
  });
  console.log("collectionTokenAccount", collectionTokenAccount.toBase58());

  const modifyComputeUnits = anchor.web3.ComputeBudgetProgram.setComputeUnitLimit({
    units: 500_000,
  });

  const feeMint = new PublicKey(tokenContractAddressValue);//usdc

  console.log("fee:",feeMint);

  

  issuePriceValue = issuePriceValue * LAMPORTS_PER_SOL;
  console.log(issuePriceValue);
  const cardInfo = anchor.web3.PublicKey.findProgramAddressSync([Buffer.from("card"), collectionPDA.toBytes()],program.programId)[0];//nft setting
  console.log("cardInfo", cardInfo.toBase58());
  console.log("totalMintAmountValue", totalMintAmountValue);
 

  try {

    const tx =  await program.methods
    .createCollection(
      {
        name: nameValue,      //nft名称
        symbol: symbolValue, //nft符号非描述
        uri: uri,  //uri
        feeRecipient: feeMint,
        price: new BN(issuePriceValue),// 带精度  1000000才是1usdt
        limit: totalMintAmountValue ,
        timestamp: new BN(timestamp),
      }
    )
    .accounts({
      authority: provider.wallet.publicKey,
      collectionMint: collectionPDA,
      metadataAccount: collectionMetadataPDA,
      masterEdition: collectionMasterEditionPDA,
      tokenAccount: collectionTokenAccount,
      cardInfo: cardInfo,
      tokenProgram: TOKEN_PROGRAM_ID,
      associatedTokenProgram: ASSOCIATED_PROGRAM_ID,
      systemProgram: SystemProgram.programId,
      tokenMetadataProgram: METADATA_PROGRAM,
      rent: SYSVAR_RENT_PUBKEY,
    })
    .preInstructions([modifyComputeUnits])
    .rpc();

  console.log("Your transaction signature", tx);


 } catch (error) {
    
   if (error instanceof AnchorError) {
     
     
     const code = error.error.errorCode.code ;
     const number = error.error.errorCode.number ;
      const  message = error.error.errorMessage;
     
     console.error('捕获到的错误: ', code,number,message);
     // 在这里处理错误，例如显示错误消息给用户
   } else {
     // 处理其他类型的错误
     console.error('未知错误: ', error);
   }
 }

}



const handleSubmit = async (event) => {

  event.preventDefault();
  let reg = /^[0-9]+([.]{1}[0-9]+){0,1}$/
  if (!reg.test(issuePrice.value)) {
    alert('价格请输入整数或者小数');
    return
  } 

  store.commit('initWorkspace', {
      callback: () => {
        create();
      }
    });



};
</script>

<style scoped>
.form-page {
color: #ffffff; /* 文字颜色为白色，以提高对比度 */
background-color: #333333; /* 表单页面背景颜色 */
padding: 20px; /* 添加内边距 */
border-radius: 8px; /* 添加圆角 */
width: 80%; /* 调整宽度为屏幕的80% */
max-width: 700px; /* 最大宽度限制 */
margin: 20px auto; /* 增加上下边距并水平居中 */
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}

.form-group {
margin-bottom: 15px; /* 减少底部边距 */
}

label {
display: block;
margin-bottom: 5px; /* 减少标签下边距 */
color: #bbbbbb; /* 标签文字颜色稍微淡一些，以区分输入框 */
font-size: 0.9em; /* 减小字体大小 */
}

.data-display {
padding: 10px;
background-color: #444444; /* 数据显示背景颜色 */
color: #dddddd; /* 数据显示文字颜色 */
border-radius: 4px; /* 数据显示圆角 */
margin-bottom: 10px; /* 数据显示下边距 */
word-wrap: break-word; /* 防止内容溢出 */
}

input[type="number"],
input[type="text"],
input[type="datetime-local"] {
width: 100%; /* 调整宽度为100% */
padding: 10px;
background-color: #444444; /* 输入框背景颜色 */
color: #dddddd; /* 输入框文字颜色 */
border: 1px solid #555555; /* 输入框边框颜色 */
border-radius: 4px; /* 输入框圆角 */
box-sizing: border-box; /* 确保宽度包括内边距和边框 */
}

button {
padding: 10px 20px;
background-color: #0056b3; /* 按钮背景颜色 */
color: white;
border: none;
border-radius: 4px; /* 按钮圆角 */
cursor: pointer;
transition: background-color 0.3s; /* 添加过渡效果 */
font-size: 0.9em; /* 减小字体大小 */
margin-top: 15px; /* 减少按钮上边距 */
}

button:hover {
background-color: #004080; /* 鼠标悬停时的按钮背景颜色 */
}

.pin-image {
display: block;
max-width: 100%; /* 确保图片不会超出容器宽度 */
height: auto; /* 高度自动调整 */
margin-top: 15px; /* 在图片上方添加间距 */
border-radius: 4px; /* 图片圆角 */
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 为图片添加阴影 */
}
</style>

